<template>
  <AuthLayout>
    <template #header>
      <h2 class="register-title">用户注册</h2>
    </template>

    <form @submit.prevent="handleRegister" class="register-form">
      <!-- 用户名 -->
      <div class="form-row">
        <label for="username" class="form-label">用　户</label>
        <div class="input-wrapper">
          <input
            type="text"
            id="username"
            v-model="form.username"
            placeholder="请输入用户名(3-20位)"
            @blur="validateUsername"
          />
          <span class="error-tip" v-if="errors.username">{{ errors.username }}</span>
        </div>
      </div>

      <!-- 邮箱 -->
      <div class="form-row">
        <label for="email" class="form-label">邮　箱</label>
        <div class="input-wrapper">
          <input
            type="email"
            id="email"
            v-model="form.email"
            placeholder="请输入邮箱"
            @blur="validateEmail"
          />
          <span class="error-tip" v-if="errors.email">{{ errors.email }}</span>
        </div>
      </div>

      <!-- 密码 -->
      <div class="form-row">
        <label for="password" class="form-label">密　码</label>
        <div class="input-wrapper">
          <input
            type="password"
            id="password"
            v-model="form.password"
            placeholder="请输入密码(6-40位)"
            @blur="validatePassword"
          />
          <span class="error-tip" v-if="errors.password">{{ errors.password }}</span>
        </div>
      </div>

      <!-- 确认密码 -->
      <div class="form-row">
        <label for="confirmPassword" class="form-label">确　认</label>
        <div class="input-wrapper">
          <input
            type="password"
            id="confirmPassword"
            v-model="form.confirmPassword"
            placeholder="请再次输入密码"
            @blur="validateConfirmPassword"
          />
          <span class="error-tip" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</span>
        </div>
      </div>

      <!-- 验证码 -->
      <div class="form-row">
        <label class="form-label">验　证</label>
        <div class="input-wrapper">
          <div class="verification-group">
            <input
              type="text"
              v-model="form.verificationCode"
              placeholder="验证码"
              @blur="validateVerificationCode"
              class="verification-input"
            />
            <button
              type="button"
              class="btn-get-verification"
              @click="sendVerificationCode"
              :disabled="!isEmailValid || isSendingCode"
            >
              {{ isSendingCode ? `${countdown}s后重发` : '获取验证码' }}
            </button>
          </div>
          <span class="error-tip" v-if="errors.verificationCode">{{ errors.verificationCode }}</span>
        </div>
      </div>

      <!-- 注册按钮 -->
      <div class="form-actions">
        <button type="submit" class="btn-register" :disabled="isSubmitting">
          {{ isSubmitting ? '注册中...' : '注　册' }}
        </button>
      </div>
    </form>

    <template #footer>
      <div class="auth-footer-link">
        已有账号？<router-link to="/">立即登录</router-link>
      </div>
    </template>
  </AuthLayout>
</template>

<script>
import AuthLayout from '@/layouts/AuthLayout'
import { register, sendVerificationCode } from '@/api/user'

export default {
  components: {
    AuthLayout
  },
  data() {
    return {
      form: {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        verificationCode: ''
      },
      errors: {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        verificationCode: ''
      },
      isSubmitting: false,
      isSendingCode: false,
      countdown: 60,
      countdownTimer: null,
      emailRegex: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
    }
  },
  computed: {
    isEmailValid() {
      return this.emailRegex.test(this.form.email)
    },
    isFormValid() {
      return (
        !this.errors.username &&
        !this.errors.email &&
        !this.errors.password &&
        !this.errors.confirmPassword &&
        !this.errors.verificationCode &&
        this.form.username &&
        this.form.email &&
        this.form.password &&
        this.form.confirmPassword &&
        this.form.verificationCode
      )
    }
  },
  methods: {

    // 发送验证码
    async sendVerificationCode() {
      if (!this.isEmailValid) {
        this.errors.email = '请输入正确的邮箱'
        return
      }
      this.errors.email = ''
      this.isSendingCode = true
      try {
        await sendVerificationCode({ email: this.form.email })
        this.$message.success('验证码已发送')
        // 开始倒计时
        this.countdown = 60
        this.countdownTimer = setInterval(() => {
          if (this.countdown <= 1) {
            clearInterval(this.countdownTimer)
            this.isSendingCode = false
            this.countdown = 60
          } else {
            this.countdown--
          }
        }, 1000)
      } catch (error) {
        this.$message.error(error.message || '发送失败')
        this.isSendingCode = false
      }
    },

    // 提交注册
    async handleRegister() {
      // 验证所有字段
      this.validateUsername()
      this.validateEmail()
      this.validatePassword()
      this.validateConfirmPassword()
      this.validateVerificationCode()
      
      if (!this.isFormValid) {
        this.$message.warning('请完善表单')
        return
      }

      this.isSubmitting = true
      
      try {
        // 调用注册API
        await register({
          username: this.form.username,
          email: this.form.email,
          password: this.form.password,
          code: this.form.verificationCode
        })
        this.$message.success('注册成功')
        this.$router.push('/')
      } catch (error) {
        this.$message.error(error.msg || '注册失败')
      } finally {
        this.isSubmitting = false
      }
    },

    // 表单验证方法
    validateUsername() {
      if (!this.form.username) {
        this.errors.username = '请输入用户名'
      } else if (this.form.username.length < 3 || this.form.username.length > 20) {
        this.errors.username = '3-20位字符'
      } else {
        this.errors.username = ''
      }
    },
    validateEmail() {
      if (!this.form.email) {
        this.errors.email = '请输入邮箱'
      } else if (!this.isEmailValid) {
        this.errors.email = '邮箱格式错误'
      } else {
        this.errors.email = ''
      }
    },
    validatePassword() {
      if (!this.form.password) {
        this.errors.password = '请输入密码'
      } else if (this.form.password.length < 6 || this.form.password.length > 40) {
        this.errors.password = '6-40位字符'
      } else {
        this.errors.password = ''
        if (this.form.confirmPassword) {
          this.validateConfirmPassword()
        }
      }
    },
    validateConfirmPassword() {
      if (!this.form.confirmPassword) {
        this.errors.confirmPassword = '请再次输入密码'
      } else if (this.form.password !== this.form.confirmPassword) {
        this.errors.confirmPassword = '密码不一致'
      } else {
        this.errors.confirmPassword = ''
      }
    },
    validateVerificationCode() {
      if (!this.form.verificationCode) {
        this.errors.verificationCode = '请输入验证码'
      } else if (this.form.verificationCode.length !== 6) {
        this.errors.verificationCode = '6位验证码'
      } else {
        this.errors.verificationCode = ''
      }
    }
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  }
}
</script>

<style scoped>
/* 标题样式 */
.register-title {
  margin-bottom: 1.5rem;
  text-align: center;
}

/* 表单整体 */
.register-form {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

/* 每一行表单项 */
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 1.8rem; /* 增加间距容纳错误提示 */
  position: relative;
}

/* 标签样式 */
.form-label {
  display: inline-block;
  width: 3em;
  margin-right: 15px;
  font-weight: 500;
  color: #333;
  text-align: justify;
  text-align-last: justify;
}

/* 输入框包裹 */
.input-wrapper {
  flex: 1;
  position: relative;
}

/* 输入框样式 */
.form-row input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  box-sizing: border-box;
}

/* 错误提示 */
.error-tip {
  position: absolute;
  right: 0;
  bottom: -1.2rem;
  font-size: 0.75rem;
  color: #f56c6c;
}

/* 验证码组样式 */
.verification-group {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.verification-input {
  flex: 1 1 0;
  min-width: 0;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  height: 44px;
  box-sizing: border-box;
}

.btn-get-verification {
  flex: none;
  width: 120px;
  height: 44px;
  padding: 0;
  background-color: #f0f2f5;
  color: #4a6cf7;
  border: 1px solid #4a6cf7;
  border-radius: 4px;
  font-size: 0.95rem;
  cursor: pointer;
  margin-left: 8px;
  transition: background 0.2s;
}

.btn-get-verification:disabled {
  color: #999;
  border-color: #ddd;
  background-color: #f5f5f5;
  cursor: not-allowed;
}

/* 保证验证码区域与其他表单项高度一致 */
.form-row .verification-group {
  height: 44px;
}

/* 注册按钮区域 */
.form-actions {
  margin-top: 2rem;
  display: flex;
  justify-content: center;
}

.btn-register {
  width: 100%;
  padding: 0.9rem 0;
  background-color: #4a6cf7;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 1.1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
  letter-spacing: 0.2em;
}

.btn-register:disabled {
  background-color: #b3c6fa;
  cursor: not-allowed;
  color: #fff;
}

/* 底部链接 */
.auth-footer-link {
  margin-top: 2rem;
  text-align: center;
  color: #888;
  font-size: 0.95rem;
}
.auth-footer-link a {
  color: #4a6cf7;
  text-decoration: none;
  margin-left: 0.5em;
}
.auth-footer-link a:hover {
  text-decoration: underline;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .form-row {
    flex-direction: column;
    align-items: flex-start;
  }
  .form-label {
    width: auto;
    margin-right: 0;
    margin-bottom: 0.5rem;
    text-align: left;
    text-align-last: left;
  }
  .input-wrapper {
    width: 100%;
  }
  .verification-group {
    width: 100%;
    gap: 8px;
  }
  .verification-input {
    width: 60%;
    min-width: 0;
    padding: 0.75rem 1rem;
    height: 40px;
  }
  .btn-get-verification {
    width: 40%;
    height: 40px;
    margin-left: 0;
  }
  .btn-register {
    padding: 0.8rem 0;
    font-size: 1rem;
  }
}
</style>
